package com.wh.wisdomsite.xbox.st.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wh.wisdomsite.xbox.ba.dao.SysSequenceMapper;
import com.wh.wisdomsite.xbox.ba.entity.CommonFile;
import com.wh.wisdomsite.xbox.ba.service.ICommonFileService;
import com.wh.wisdomsite.xbox.core.XboxException;
import com.wh.wisdomsite.xbox.st.dao.*;
import com.wh.wisdomsite.xbox.st.entity.*;
import com.wh.wisdomsite.xbox.st.service.IPurchaseApplyService;
import com.wh.wisdomsite.xbox.st.service.IPurchaseFileService;
import com.wh.wisdomsite.xbox.utils.Const;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.*;

/**
 * 采购申请serviceImpl
 * @author 刘旭
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.st.service.impl
 * @date 2018年12月24日 14:45
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Service("purchaseApplyService")
@Transactional(rollbackFor = {Exception.class, RuntimeException.class})
public class PurchaseApplyServiceImpl extends ServiceImpl<PurchaseApplyMapper, PurchaseApply> implements IPurchaseApplyService {

    private static final Log logger = LogFactory.getLog(PurchaseApplyServiceImpl.class);

    @Autowired
    private PurchaseApplyMapper purchaseApplyMapper;

    @Autowired
    private PurchaseDetailMapper purchaseDetailMapper;

    @Autowired
    private ContractDetailMapper contractDetailMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private IPurchaseFileService iPurchaseFileService;

    @Autowired
    private ICommonFileService iCommonFileService;

    @Autowired
    private SysSequenceMapper sysSequenceMapper;

    /**
     * 获取序列前面的补足零
     */
    private static final Map<String, String> numberMap;
    static
    {
        numberMap = new HashMap<String, String>();
        numberMap.put("1", "000");
        numberMap.put("2", "00");
        numberMap.put("3", "0");
    }

    @Autowired
    private PurchaseFileMapper purchaseFileMapper;


    @Override
    public Page<Map<String, Object>> getReportedPage(Page page, Wrapper<PurchaseApply> wrapper) {
        SqlHelper.fillWrapper(page, wrapper);
        page.setRecords(this.baseMapper.getReportedPage(page, wrapper));
        return page;
    }

    @Override
    public Map<String, Object> getMapById(Serializable id) {
        return purchaseApplyMapper.getMapById(id);
    }

    @Override
    public Page<Map<String, Object>> getMapsPage(Page page, Wrapper<PurchaseApply> wrapper) {
        SqlHelper.fillWrapper(page,wrapper);
        page.setRecords(this.baseMapper.getMapsPage(page,wrapper));
        return page;
    }

    @Override
    public Page<Map<String, Object>> getMapsListPage(Page page, Wrapper<PurchaseApply> wrapper) {
        SqlHelper.fillWrapper(page,wrapper);
        page.setRecords(this.baseMapper.getMapsListPage(page,wrapper));
        return page;
    }

    @Override
    public Page<PurchaseApply> selectPage(Page<PurchaseApply> page, PurchaseApply purchaseApply, String compCode) {
        page.setRecords(purchaseApplyMapper.selectPage(page, purchaseApply, compCode));
        return page;
    }

    @Override
    public Page<PurchaseApply> queryPage(Page<PurchaseApply> page, PurchaseApply purchaseApply,String compCode) {
        page.setRecords(purchaseApplyMapper.queryPage(page, purchaseApply,compCode));
        return page;
    }

    @Override
    public void checkPurchaseApply(String purId) throws Exception{
        //合同内的采购清单对合同已请购量进行数量更新
        List<Map<String, Object>> sumPurChasedNum = purchaseApplyMapper.getSumPurChasedNumByPurId(purId);
        if(sumPurChasedNum.size() > 0){
            for(Map<String, Object> map : sumPurChasedNum){
                String purType = (String)map.get("purType");
                if("1".equals(purType)){
                    ContractDetail contractDetail = new ContractDetail();
                    contractDetail.setCdId((String)map.get("coId"));
                    contractDetail.setPurchasedNum(Double.valueOf(map.get("sunPurchasedNum").toString()));
                    contractDetailMapper.updateById(contractDetail);
                }
            }
        }
    }

    @Override
    public void savePurchaseApply(PurchaseApply purchaseApply, CommonFile commonFile, String fileName, String pfId, String userId, String compCode) throws Exception {
        //判断方法是否已经存在,存在即更新.否则为添加
        if (StringUtils.isNotEmpty(purchaseApply.getPurId())) {
            logger.info("修改采购申请-->>开始");
            //设置附件信息
            if(StringUtils.isNotEmpty(commonFile.getFileId())) {
                PurchaseFile purchaseFile = iPurchaseFileService.selectById(pfId);
                //源附件不存在, 则添加新附件
                if(null == purchaseFile){
                    if(StringUtils.isNotEmpty(commonFile.getFileId())){
                        //添加附件
                        addFile(fileName, purchaseApply, commonFile, userId, compCode);
                    }
                }

                //源附件存在，则更新
                if(null != purchaseFile){
                    if(!purchaseFile.getFileId().equals(commonFile.getFileId())){
                        commonFile.setName(fileName);
                        purchaseFile.setFileId(commonFile.getFileId());
                        iPurchaseFileService.updateById(purchaseFile);
                        addCommonFile(purchaseApply, commonFile, userId,compCode);
                    }
                }

            }
            purchaseApply.setUpdateBy(userId);
            purchaseApply.setUpdateDate(new Date());
            purchaseApplyMapper.updateById(purchaseApply);
            logger.info("修改采购申请-->>结束");
        } else {
            logger.info("添加采购申请-->>开始");
            purchaseApply.setPurId(UUID.randomUUID().toString().replace("-", ""));
            //采购单号 规制指定
            String purCode = getPurCodeNum(purchaseApply.getCoId(),purchaseApply.getPurType());
            purchaseApply.setPurCode(purCode);
            purchaseApply.setCreateBy(userId);
            if(StringUtils.isNotEmpty(commonFile.getFileId())){
                //添加附件
                addFile(fileName, purchaseApply, commonFile, userId, compCode);
            }
            purchaseApply.setReportState("1");
            purchaseApply.setCheckState("0");
            purchaseApply.setDataState("1");
            purchaseApply.setCreateDate(new Date());
            purchaseApply.setPurDate(new Date());
            purchaseApplyMapper.insert(purchaseApply);
            logger.info("添加采购申请-->>结束");
        }
    }


    /**
     * 添加附件信息
     * @param fileName
     * @param purchaseApply
     * @param commonFile
     * @param userId
     * @param compCode
     */
    public void addFile(String fileName, PurchaseApply purchaseApply, CommonFile commonFile, String userId, String compCode){
        //1. 添加公共附件关联信息
        //2. 添加采购附件信息
        commonFile.setName(fileName);
        addCommonFile(purchaseApply, commonFile, userId, compCode);
        PurchaseFile purchaseFile = new PurchaseFile();
        purchaseFile.setPfId(UUID.randomUUID().toString().replace("-",""));
        purchaseFile.setFileId(commonFile.getFileId());
        purchaseFile.setPurId(purchaseApply.getPurId());
        iPurchaseFileService.insert(purchaseFile);
    }






    @Override
    public String getNumberFront(String valueLen) {
        if(StringUtils.isNotEmpty(valueLen)){
            return numberMap.get(valueLen);
        }else{
            return null;
        }
    }

    /**
     * 添加附件信息
     * @param purchaseApply
     * @param commonFile
     * @param curUser
     */
    private void addCommonFile(PurchaseApply purchaseApply,CommonFile commonFile, String curUser,String compCode) {
        commonFile.setFkId(purchaseApply.getPurId());
        commonFile.setCreateby(curUser);
        commonFile.setCreatedate(new Date());
        commonFile.setCompCode(compCode);
        iCommonFileService.insert(commonFile);
    }

    /**
     * 获取采购单号
     * @param coId
     * @param purType
     * @return
     */
    private String getPurCodeNum(String coId,String purType){
        //采购单号
        String purCode = "";
        //序列名（查询条件）
        String seqName = "";
        //截取合同单号
        Contract contract = contractMapper.selectById(coId);
        String[] coCodeArr = contract.getCoCode().split("_");
        String coCodeNum = coCodeArr[1];
        //判断合同类型给定前缀及序列名
        if("1".equals(purType)){
            purType = "CGN";
            seqName = Const.PURCODE_CGN_SEQ;
        }else{
            purType = "CGW";
            seqName = Const.PURCODE_CGW_SEQ;
        }
        //获取序列
        Map<String,Object> parmaMap = new HashMap<>();
        parmaMap.put("seqName",seqName);
        parmaMap.put("seqValue",null);
        sysSequenceMapper.getSeqNextVal(parmaMap);
        Object valSeq = parmaMap.get("seqValue");
        if(valSeq == null){
            throw new XboxException("采购单号序列为空，保存失败");
        }
        //计算序列长度，依据长度值给定前缀
        String valSeqStr = String.valueOf(valSeq);
        String seqNumLen = String.valueOf(valSeqStr.length());
        String numberFront = numberMap.get(seqNumLen);
        //拼接采购单号
        purCode =  purType + "_" + coCodeNum + "_" + numberFront + valSeqStr;
        return purCode;
    }


    @Override
    public void delPurchaseByPurId(String purId) throws Exception {
        try{

            logger.info("删除请购->>delPurchaseByPurId->>开始");
            //1.删除请购数据
            purchaseApplyMapper.deleteById(purId);

            //2.删除请购清单
            EntityWrapper<PurchaseDetail> ewPurchaseDetail = new EntityWrapper<>();
            ewPurchaseDetail.eq("purId",  purId);
            purchaseDetailMapper.delete(ewPurchaseDetail);

            //3.删除请购附件
            EntityWrapper<PurchaseFile> ewPurchaseFile = new EntityWrapper<>();
            ewPurchaseFile.eq("purId",  purId);
            purchaseFileMapper.delete(ewPurchaseFile);
            logger.info("删除请购->>delPurchaseByPurId->>结束");
        } catch (Exception e){
            e.printStackTrace();
            logger.error("删除请购->>delPurchaseByPurId->>Exception " + e.getMessage());
            throw new Exception("删除请购->>delPurchaseByPurId->>Exception " + e.getMessage());

        }

    }

    @Override
    public PurchaseApply getPurchaseApplyByPurId(String purId) {
        return purchaseApplyMapper.getPurchaseApplyByPurId(purId);
    }
}
